//注册路由组件

import React, { Component } from 'react'
import {
    NavBar,
    WingBlank,
    List,
    InputItem,
    WhiteSpace,
    Button,
    Radio,
    Toast
} from 'antd-mobile'
import Logo from '../../components/logo/logo'
import {connect} from 'react-redux'
import {Redirect} from 'react-router-dom'
import {register} from '../../redux/actions'


const ListItem = List.Item

class Register extends Component {
    state = {
        username:'',
        password:'',
        password2:'',//确认密码
        type:'zhuren'//用户类型名称  
    }

    register = () =>{
        //console.log(this.state)    
        this.props.register(this.state)
    }
//处理输入数据的改变，更新对应的状态
    handleChange = (name,val) =>{
        //更新状态
        this.setState({
            [name]:val //属性名不是name而是name变量的值
        })
    }

    toLogin = () =>{
        this.props.history.replace('/login')
    }

    render() {
        const {type} = this.state
        const {msg,redirecTo} = this.props.user
        //如果redirecTo有值，就需要重定向
        if(redirecTo){
            return  <Redirect to={redirecTo}/>
        }
        if(msg){
            Toast.fail(msg)
        }
        return (
            <div>
                <NavBar>狗&nbsp;狗&nbsp;直&nbsp;聘</NavBar>
                <Logo />
                <WingBlank>
                    <List>
                        <WhiteSpace></WhiteSpace>
                        <InputItem placeholder='请输入用户名' onChange={val => {this.handleChange('username',val)}}>用户名:</InputItem>
                        <WhiteSpace></WhiteSpace>
                        <InputItem placeholder='请输入密码' type="password" onChange={val => {this.handleChange('password',val)}}>密&nbsp;&nbsp;&nbsp;码:</InputItem>
                        <WhiteSpace></WhiteSpace>
                        <InputItem placeholder='请确认密码' type="password" onChange={val => {this.handleChange('password2',val)}}>确认密码:</InputItem>
                        <WhiteSpace></WhiteSpace>
                        <ListItem>
                            <span>用户类型</span>&nbsp;&nbsp;&nbsp;
                            <Radio checked={type==='zhuren'?true:false} onChange={() => this.handleChange('type','zhuren')}>养狗的</Radio>&nbsp;&nbsp;&nbsp;
                            <Radio checked={type==='customer'?true:false} onChange={() => this.handleChange('type','customer')}>买狗的</Radio>&nbsp;&nbsp;&nbsp;
                        </ListItem>
                        <Button type="primary" onClick={this.register}>注册</Button>
                        <WhiteSpace></WhiteSpace>
                        <WhiteSpace></WhiteSpace>
                        <Button type="warning" onClick={this.toLogin}>已有账户</Button>
                    </List>
                </WingBlank>
            </div>
        )
    }
}
export default connect(
    state => ({user:state.user}),
    {register}
)(Register)